﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace Clmp.WebForm.CallBack
{
    /// <summary>
    ///CallBackManager 的摘要说明
    /// </summary>
    public class CallBackManager
    {
        public CallBackManager(Page page)
        {
            this.page = page;
        }

        private Page page;
        public delegate string CallbackDelegate(string eventArgument);
        Dictionary<string, string> ScriptDic = new Dictionary<string, string>();

        /// <summary>
        /// 获取回调脚本
        /// </summary>
        /// <param name="name">回调名称</param>
        /// <param name="argument">回调参数</param>
        /// <param name="clientCallback">客户端函数</param>
        /// <param name="context">回调前执行方法</param>
        /// <returns>回调脚本</returns>
        public string CreateCallbackEventScript(string name, string argument, string clientCallback, string context, CallbackDelegate callback)
        {
            CallBackHost host = new CallBackHost();
            page.Controls.Add(host);
            host.Callback = callback;
            string script = page.ClientScript.GetCallbackEventReference(host, argument, clientCallback, context);
            ScriptDic.Add(name, script);

            return script;
        }

        public string CreateCallbackEventScript(string name, string argument, string clientCallback, string context, CallbackDelegate callback, string clientErrorCallback)
        {
            CallBackHost host = new CallBackHost();
            page.Controls.Add(host);
            host.Callback = callback;
            string script = page.ClientScript.GetCallbackEventReference(host, argument, clientCallback, context, clientErrorCallback, false);
            ScriptDic.Add(name, script);

            return script;
        }

        public string GetCallbackScript(string name)
        {
            string script;
            ScriptDic.TryGetValue(name, out script);
            return script;
        }
    }
}